import Qs from 'querystring';
import axios from 'axios'
// const axios = require('axios')
// import {proxy} from '@/config'
// const config = require('@src/config-client')
import config from '@src/config-client';

const
    devMode = process.env.NODE_ENV !== 'production',
    // proxyTable = proxy;
proxyTable = config.proxy;

axios.defaults.baseURL = devMode ? '//localhost:3003' : '//39.105.144.7:5002';

axios.defaults.withCredentials = true;

axios.defaults.crossDomain =  true;

axios.defaults.headers.common = {
    'Accept': 'application/json, text/plain, */*',
    'X-Requested-With': 'XMLHttpRequest',
    'Cache-Control': 'no-cache'
};

axios.defaults.paramsSerializer = function(params) {
    return Qs.stringify(params)
};

axios.defaults.transformRequest = [data => {
    for(let item in data) {
        if (typeof data[item] === 'object'){
            data[item] = JSON.stringify(data[item])
        }
    }
    return Qs.stringify(data)
}];

export default param => {
    let
        url = param.url.charAt(0) === '/' ? param.url : '/' + param.url,
        urlApi = ['/' + url.split('/')[1]];

    param.url = url.replace(urlApi,proxyTable[urlApi]);
    console.log("URL---",param.url);

    return axios(param).then(res => {
        if (res.data && res.data.code && (res.data.code == '200')) {
            return res;
        }
        else {
            if (res.data.ERROR) {
                window.vm.$notify({
                    title: res.data.ERROR,
                    type: 'error'
                });
            }
            return Promise.reject({
                msg: res.data.ERROR
            });
        }
    }, err => {
        console.log(err);

        window.vm.$notify({
            title: '网络错误!',
            type: 'error'
        });

        return Promise.reject({
            msg: '网络错误!'
        });
    })
};

